<template>
  <div class="spec-manage">
    <!-- 1. 动态添加规格维度和选项 -->
    <el-card>
      <div slot="header">规格模型</div>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAddModal">添加模型</el-button>
        </el-col>
        <el-col :span="6">
          <el-select v-model="specId" placeholder="请选择" @change="specChange">
            <el-option
              v-for="item in specList"
              :label="item.typeName"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="warning" @click="handleEditModal"
            >修改模型</el-button
          >
        </el-col> -->
      </el-row>
      <el-form
        style="margin-top: 40px"
        ref="checkForm"
        v-model="checkForm"
        label-width="80px"
      >
        <el-form-item
          :label="item.name"
          v-for="(item, index) in checkList"
          :key="index"
        >
          <el-checkbox
            v-for="(opt, index) in item.optionNames"
            :key="index"
            :label="opt.id"
            v-model="opt.checked"
            >{{ opt.itemName }}</el-checkbox
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 2. 生成规格组合 -->
    <el-card class="box-card" v-if="dimensions.length > 0">
      <h3>规格组合</h3>
      <el-button
        type="success"
        style="margin-bottom: 20px"
        @click="generateCombinations"
        >生成规格组合</el-button
      >
      <el-table
        v-if="combinations.length > 0"
        :data="combinations"
        border
        stripe
      >
        <el-table-column prop="optionKeyName" label="规格名称" />
        <el-table-column prop="optionKey" label="id" />
        <el-table-column prop="dimensions" label="规格详情">
          <template #default="{ row }">
            {{ row.dimensions }}
          </template>
        </el-table-column>
        <el-table-column label="售价">
          <template #default="{ row }">
            <el-input-number
              v-model="row.price"
              :min="0"
              :step="1"
              placeholder="售价"
            />
          </template>
        </el-table-column>
        <el-table-column label="市场价">
          <template #default="{ row }">
            <el-input-number
              v-model="row.costPrice"
              :min="0"
              :step="1"
              placeholder="市场价"
            />
          </template>
        </el-table-column>
        <el-table-column label="会员价">
          <template #default="{ row }">
            <el-input-number
              v-model="row.memberPrice"
              :min="0"
              :step="1"
              placeholder="会员价"
            />
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template #default="{ row }">
            <el-input-number
              v-model="row.storeCount"
              :min="0"
              placeholder="库存"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 保存按钮 -->
    <el-button
      type="primary"
      @click="saveCombinations"
      style="margin-top: 20px; margin-left: 20px"
      v-if="combinations.length > 0"
      :loading="btnLoad"
    >
      保存规格组合
    </el-button>
    <el-dialog title="配置规格" :visible.sync="dialogVisible" width="500px">
      <div>
        <el-form ref="form1" label-width="80px">
          <el-form-item label="模型名称">
            <el-input
              style="width: 200px"
              v-model="itemName"
              placeholder="请输入模型名称"
            />
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <div
          v-for="(dimension, index) in dimensions"
          :key="index"
          class="dimension-item"
        >
          <el-form label-width="80px" ref="form" size="small">
            <!-- 维度名称 -->
            <el-form-item label="名称">
              <el-input
                style="width: 200px"
                v-model="dimension.name"
                placeholder="请输入维度名称"
              />
            </el-form-item>
            <!-- 维度选项 -->
            <el-form-item label="选项">
              <el-tag
                v-for="(option, optIndex) in dimension.options"
                :key="optIndex"
                closable
                @close="removeOption(index, optIndex)"
              >
                {{ option }}
              </el-tag>
              <el-input
                v-model="dimension.newOption"
                placeholder=""
                size="small"
                @keyup.enter.native="addOption(index)"
              />
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="danger"
                size="small"
                @click="removeDimension(index)"
                >删除</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-button type="primary" @click="addDimension">新增规格</el-button>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="btnLoad" type="primary" @click="submitDime"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveProductSpecItem,
  queryProductSpecType,
  getProductSpecItem,
  saveProductSpecGoodsPrice,
  showProductSpecDetail,
} from "@/api/company/localProduct";
export default {
  name: "SpecManage",
  data() {
    return {
      dialogVisible: false,
      specId: null,
      itemName: null,
      dimensions: [
        {
          name: null,
          options: [], // 用户添加的选项
          newOption: "", // 当前输入框的值
        },
      ],
      checkForm: {
        checkList: [],
      },
      combinations: [], // 生成的规格组合
      specList: [], //模型列表
      checkList: [],
      btnLoad: false,
      typeName: null,
    };
  },
  created() {
    this.getSpecList();
    this.getSpecDetail();
  },
  methods: {
    // 获取规格详情
    getSpecDetail() {
      const productId = this.$route.query.id;
      showProductSpecDetail({ productId }).then((res) => {
        if (res.data) {
          this.checkList = res.data.spec_detail.itemDetails;
          this.combinations = res.data.product_spec_detail;
          this.typeName = res.data.spec_detail.itemName;
          this.specId = res.data.spec_detail.itemName.id;
        }
      });
    },
    // 选择模型
    specChange(val) {
      getProductSpecItem({ typeId: val }).then((res) => {
        this.checkList = res.data.itemDetails.map((v) => {
          v.optionNames.map((o) => {
            o.checked = false;
          });
          return v;
        });
        this.typeName = {
          name: res.data.itemName,
          id: val,
        };
      });
    },
    handleEditModal() {},
    handleAddModal() {
      (this.dimensions = [
        {
          name: null,
          options: [], // 用户添加的选项
          newOption: "", // 当前输入框的值
        },
      ]),
        (this.dialogVisible = true);
    },
    submitDime() {
      const data = {
        itemName: this.itemName,
        itemDetails: [...this.dimensions],
      };
      this.btnLoad = true;
      saveProductSpecItem(data)
        .then((res) => {
          this.btnLoad = false;
          if (res.code == 200) {
            this.dialogVisible = false;
            this.$message.success(res.msg);
            this.getSpecList();
          }
        })
        .catch((e) => {
          this.btnLoad = false;
        });
    },
    // 获取模型列表
    getSpecList() {
      queryProductSpecType().then((res) => {
        if (res.code == 200) {
          this.specList = res.data;
        }
      });
    },
    // 动态添加新规格维度
    addDimension() {
      this.dimensions.push({
        name: "",
        options: [],
        newOption: "",
      });
    },

    // 删除规格维度
    removeDimension(index) {
      this.dimensions.splice(index, 1);
    },

    // 添加规格选项
    addOption(dimensionIndex) {
      const dimension = this.dimensions[dimensionIndex];
      if (dimension.newOption.trim()) {
        dimension.options.push(dimension.newOption.trim());
        dimension.newOption = ""; // 清空输入框
      } else {
        this.$message.error("选项不能为空");
      }
    },

    // 删除规格选项
    removeOption(dimensionIndex, optionIndex) {
      this.dimensions[dimensionIndex].options.splice(optionIndex, 1);
    },

    // 生成规格组合
    generateCombinations() {
      // 验证每个维度至少有一个选项
      // if (
      //   this.dimensions.some((dim) => !dim.name || dim.options.length === 0)
      // ) {
      //   this.$message.error("请确保每个规格维度都有名称和至少一个选项");
      //   return;
      // }
      if (this.checkList.length == 0) {
        this.$message.error("请选择规格");
        return;
      }
      const validateData = this.checkList.map((dim) =>
        dim.optionNames.filter((o) => o.checked)
      );
      if (
        validateData.some((v) => {
          return v.filter((o) => o.checked).length == 0;
        })
      ) {
        this.$message.error("请确保每个规格维度都有名称和至少一个选项");
        return;
      }
      // 计算规格组合（笛卡尔积）
      // const result = this.cartesianProduct(
      //   ...this.dimensions.map((dim) =>
      //     dim.options.map((option) => ({ [dim.name]: option}))
      //   )
      // );
      const data = this.checkList.map((dim) =>
        dim.optionNames
          .filter((o) => o.checked)
          .map((option) => ({
            name: option.itemName,
            id: option.id,
            spec: dim.name,
          }))
      );
      const result = this.cartesianProduct(...data);
      // const result = this.cartesianProduct(
      //   ...this.dimensions.map((dim) =>
      //     dim.options.map((option) => ({ [dim.name]: option }))
      //   )
      // );
      // 格式化组合结果
      this.combinations = result.map((item) => {
        const dimensions = Object.entries(item)
          .map(([key, value]) => {
            return `${value.spec}: ${value.name}`;
          })
          .join(", ");
        console.log(item, "item");
        return {
          optionKeyName: Object.values(item.map((v) => v.name)).join("_"),
          optionKey: Object.values(item.map((v) => v.id)).join("_"),
          dimensions,
          price: 0, // 售价
          costPrice: 0, // 市场价
          memberPrice: 0, //会员价
          storeCount: 0, // 默认库存
        };
      });
    },

    // 笛卡尔积算法
    cartesianProduct(...arrays) {
      // 初始值为包含一个空数组的数组
      return arrays.reduce(
        (acc, curr) => {
          const result = [];
          // 遍历现有结果和当前层的所有元素，生成新组合
          acc.forEach((a) => {
            curr.forEach((c) => {
              result.push([...a, c]);
            });
          });
          return result;
        },
        [[]]
      ); // 初始值为一个空数组
    },

    // 保存规格组合
    saveCombinations() {
      const data = this.combinations.map((v) => ({
        ...v,
        productId: this.$route.query.id,
      }));
      this.btnLoad = true;
      const saveData = {
        specDetail: {
          itemName: this.typeName,
          itemDetails: this.checkList,
        },
        productSpecGoodsPrices: [...data],
      };
      saveProductSpecGoodsPrice(saveData)
        .then((res) => {
          this.btnLoad = false;
          this.$message.success(res.msg);
        })
        .catch((e) => {
          this.btnLoad = false;
        });
    },
  },
};
</script>
<style scoped>
.box-card {
  margin-bottom: 20px;
}

.dimension-item {
  margin-bottom: 15px;
}

.dimension-item .el-tag {
  margin-right: 5px;
}
</style>
